package bing.netty.example.timewithpojo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
 * @author LBH
 * startup discardserver
 */
public class TimeServer {

	private int port;
	
	public TimeServer(int port){
		this.port=port;
	}
	
	public void run() throws Exception{
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try{
			ServerBootstrap server=new ServerBootstrap();
			server.group(bossGroup, workerGroup)
			      .channel(NioServerSocketChannel.class)
			      .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
		                 @Override
		                 public void initChannel(SocketChannel ch) throws Exception {
		                     ch.pipeline().addLast(new TimeEncoder(),new TimeServerHandler());
		                 }
		             })
		             .option(ChannelOption.SO_BACKLOG, 128)
		             .childOption(ChannelOption.SO_KEEPALIVE, true);
			
			//bind and start to accept incoming connections
			ChannelFuture cf=server.bind(port).sync();
			// Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            cf.channel().closeFuture().sync();
		}finally{
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

		int port;
		if(args.length>0){
			port=Integer.parseInt(args[0]);
		}else{
			port=8030;
		}
		new TimeServer(port).run();
	}

}
